﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using AKJ.Sharepoint.Branding.Config;
using Microsoft.SharePoint.Utilities;
using AKJ.Sharepoint.Branding.Code;
using System.Web.UI;

namespace AKJ.Sharepoint.Branding.BrandingInterceptor
{
    public class RebrandingPathInterceptor : IBrandingInterceptor
    {
        public void InterceptRequest(Page page, HttpRequest request)
        {
            // If we page did't have a master then abort
            if (page == null /*|| page.MasterPageFile == null*/)
                return;

            string currentUrl = request.RawUrl;
            bool isLayoutPath = currentUrl.Contains("_layouts/");

            // Open the custom Visual Branding Section 
            VisualBrandingSection visualBrandingSection = VisualBrandingSection.Instance();

            for (int i = 0; i < visualBrandingSection.RebrandPaths.Count; i++)
            {
                RebrandPathElement rebrandPath = visualBrandingSection.RebrandPaths[i];

                // We URLDecode if user has enter a URL like "/Shared%20Documents/Forms/AllItems.aspx" in Web.config
                if (currentUrl.ToLower().Contains(SPEncode.UrlDecodeAsUrl(rebrandPath.Path.ToLower())))
                {
                    // If this is a layouts page abort if it is not permitted
                    if (isLayoutPath && (rebrandPath.IncludelayoutsFolder == false))
                        continue;
                    
                    // If priority eq -1 then it is undefined. Use running index as priority instead.
                    int priority = rebrandPath.Priority == 0 ? i : rebrandPath.Priority;

                    if(rebrandPath.ApplyCss.File != "")
                        BrandingManager.InsertBrandingElement(BrandingElementType.AKJ_Sharepoint_Css, priority, rebrandPath.ApplyCss.File);

                    if (rebrandPath.ApplyMaster.File != "")
                        BrandingManager.InsertBrandingElement(BrandingElementType.AKJ_Sharepoint_Master, priority, rebrandPath.ApplyMaster.File);                    
                }
            }
        }        
    }
}